package pile.pay.utils;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pile.pay.entity.MemberSubsidiary;
import pile.pay.entity.Recharge;
import pile.pay.service.IMemberSubsidiaryService;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Log4j2
public class SendSubscriptionMessageTool {

    @Autowired
    private WxUtil wxUtil;

    @Autowired
    private IMemberSubsidiaryService memberSubsidiaryService;

    /**
     * 发送订阅消息
     *
     * @param
     */
    private void sendRefundNotification(Recharge recharge) {
        try{


            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + wxUtil.getAccessToken(recharge.getChannel());

            cn.hutool.json.JSONObject json = new cn.hutool.json.JSONObject();
            cn.hutool.json.JSONObject data = new cn.hutool.json.JSONObject();
            //根据用户id 查询信息
            //根据用户ID 和渠道查询用户附属表信息
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("type",recharge.getChannel());
            queryWrapper.eq("member_id",recharge.getMemberId());
            MemberSubsidiary memberSubsidiary = memberSubsidiaryService.getOne(queryWrapper);

            if(memberSubsidiary==null){
                return;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
            json.put("touser", memberSubsidiary.getOpenid());

            //跳转路径
            json.put("page", "/pages/skip/bill");

            //不同的小程序要用不同的模版
            if(recharge.getChannel()==1){
                //卫莱电微信小程序
                json.put("template_id", "lilLhfm7noOzkT-9Zg1djr7BPmSJorkXvWvHr9gHhhg");
            }else if(recharge.getChannel()==3){
                //啊凡电微信小程序
                json.put("template_id", "lilLhfm7noOzkT-9Zg1djr7BPmSJorkXvWvHr9gHhhg");
            }else {
                return;
            }
            //退款金额
            data.put("amount1", new cn.hutool.json.JSONObject().put("value", recharge.getRefundAmount()));
            //时间
            data.put("time2", new cn.hutool.json.JSONObject().put("value", sdf.format(new Date())));

            json.put("data", data);
            //发送消息
            String result = HttpClientUtil.doPostJson(url, json.toString());
            log.info("发送退款通知:"+result);
        }catch (Exception e){
            log.error("发送退款通知订阅消息报错:"+e);
        }

    }





}
